package coding.utill;

import coding.song.Song;
import coding.song.SongList;

import java.io.*;

/**
 * @创建人 xfliu
 * @创建时间 2021/9/16
 * @描述 写入歌单
 */
public class IOSong {
    private static String filePath="\\javaBigHomework\\src\\coding\\data\\song.txt";
    private static String dirPath="\\javaBigHomework\\src\\coding\\data";
    private static File dir= new File(dirPath);
    private static File file =new File(filePath);

    static {
        if (!dir.exists()){
            dir.mkdirs();
            System.out.println(dir+" mkdir success~~");
        }
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }    }
    //写入歌曲清单
    public void writerSongList(SongList songList){
        try {
            FileOutputStream fos=new FileOutputStream(filePath);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(songList);
            oos.writeBoolean(true);
            oos.flush();
            fos.close();
            oos.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //读取歌单
    public SongList readerSong(){
        SongList songList1=new SongList();
        try {
            FileInputStream fis = new FileInputStream(filePath);
            ObjectInputStream ois = new ObjectInputStream(fis);
            songList1= (SongList) ois.readObject();

            fis.close();
            ois.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return songList1;
    }

    public static void main(String[] args) {
        IOSong IOSong =new IOSong();
        SongList songList=new SongList();
        Song song=new Song("ss",1);
        Song song2=new Song("ss",2);
        songList.addSong(song);
        songList.addSong(song2);
        songList.querySong();
        IOSong.writerSongList(songList);
        IOSong.readerSong();
    }

}
